<?php

namespace App\Jobs\User;

use App\Http\Controllers\Api\Traits\PayTrait;
use App\Models\User\WxUserWithdrawal;
use App\Wen\Utils\Settings;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class UserWithdrawalQueryJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    use PayTrait;
    public $tries = 1;
    // 此id为 序号id
    protected $withdrawal_id = 0;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($withdrawal_id)
    {
        //
        $this->withdrawal_id = $withdrawal_id;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {

        // 先处理微信批次打款
        if(Settings::get('mch_transfer_to_weChat', 0) == 1){
            $provider = 'wxpay';
            $pay_type = 'mini';
            $lists = [];

            if(_empty_($this->withdrawal_id)){
                $lists = WxUserWithdrawal::whereIn('state', [3])->whereNotNull('wx_batch_id')->orderBy('id', 'desc')->limit(10)->get();
            }else{
                $withdrawal = WxUserWithdrawal::whereIn('state', [3])->whereNotNull('wx_batch_id')->where('id', $this->withdrawal_id)->first();
                if($withdrawal){
                    $lists[] = $withdrawal;
                }
            }
            if(_empty_($lists)){
                return;
            }

            try {
                foreach ($lists as $item){
                    $query_result = $this->transferBatchQuery($provider, $item->wx_batch_id, true);
                    if($query_result && !_empty_(_array_key($query_result, 'transfer_batch', []))){
                        $close_reason = '';
                        $success_time = $query_result['transfer_batch']['update_time'];

                        if($query_result['transfer_batch']['batch_status'] == 'FINISHED'){
                            // 转账完成
                        }else if($query_result['transfer_batch']['batch_status'] == 'PROCESSING' || $query_result['transfer_batch']['batch_status'] == 'ACCEPTED'){
                            // 还在处理中

                        }else if($query_result['transfer_batch']['batch_status'] == 'CLOSED'){
                            $close_reason = $query_result['transfer_batch']['close_reason'];
                            if($close_reason == 'OVERDUE_CLOSE'){
                                $close_reason = 'OVERDUE_CLOSE: 系统超时关闭，可能原因账户余额不足或其他错误';
                            }else if($close_reason == 'TRANSFER_SCENE_INVALID'){
                                $close_reason = 'TRANSFER_SCENE_INVALID: 产品被微信官方关闭';
                            }
                            WxUserWithdrawal::whereIn('wx_batch_id', $item->wx_batch_id)->where('state', 3)->update([
                                'state' => 2,
                                'refuse_tip' => $close_reason,
                            ]);
                        }


                        $transfer_detail_list = $query_result['transfer_detail_list'];
                        if(!_empty_($transfer_detail_list)){
                            $success_withdrawals = [];
                            $fail_withdrawals = [];
                            foreach ($transfer_detail_list as $detail){
                                if($detail['detail_status'] == 'SUCCESS'){
                                    $success_withdrawals[] = $detail['out_detail_no'];
                                }else if($detail['detail_status'] == 'FAIL'){
                                    $fail_withdrawals[] = $detail['out_detail_no'];
                                }else if($detail['detail_status'] == 'WAIT_PAY'){

                                }
                            }
                            if($success_withdrawals){
                                WxUserWithdrawal::whereIn('withdrawal_id', $success_withdrawals)->where('state', 3)->update(['state'=> 1, 'account_at'=>$success_time, 'account_way'=>'wxpay']);
                            }
                            if($fail_withdrawals){
                                WxUserWithdrawal::whereIn('withdrawal_id', $fail_withdrawals)->where('state', 3)->update([
                                    'state' => 2,
                                    'refuse_tip' => $close_reason,
                                ]);
                            }
                        }
                    }
                }
            }catch (\Exception $e){
                _logger_(__file__, __line__, $e->getMessage());
            }
        }

    }
}
